package com.vertxsample.samples.testjooq

import com.vertxsample.samples.core.db.HikariPoolUtil
import com.vertxsample.samples.core.web.RequestContext
import com.vertxsample.samples.testjooq.controller.JsonController
import com.zaxxer.hikari.HikariConfig
import io.vertx.core.AbstractVerticle
import io.vertx.core.Future
import io.vertx.core.Vertx
import io.vertx.core.http.HttpServerResponse
import io.vertx.ext.web.Router


class App : AbstractVerticle(){
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            val vertx = Vertx.vertx()

            vertx.deployVerticle(App())
        }
    }
    override fun start(startFuture: Future<Void>) {
        var router = customRouter(vertx)
        println("server running on 8888")
        vertx.createHttpServer().requestHandler({ handler -> router.handle(handler)}).listen(8888){ result ->
            if (result.succeeded()) {
                startFuture.complete()
            } else {
                startFuture.fail(result.cause())
            }
        }
    }
    fun customRouter(vertx : Vertx) : Router {


        val config = HikariConfig()


        config.jdbcUrl = "jdbc:db2://localhost:50400/DB"
        config.username = "gpo"
        config.password = "123456"
        config.driverClassName = "com.ibm.db2.jcc.DB2Driver"

        config.addDataSourceProperty("cachePrepStmts", "true")
        config.addDataSourceProperty("prepStmtCacheSize", "250")
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048")

        val dslContext= HikariPoolUtil.getContext(HikariPoolUtil.getConnection(HikariPoolUtil.getDataSource(config))!!)

        var router = Router.router(vertx)

        router.route("/json").handler({c ->

            JsonController(RequestContext(vertx, c,dslContext)).toJson().thenAccept {
               it-> c.response().json().end(it)
            }

         })
        return router
    }


    fun HttpServerResponse.json() : HttpServerResponse {
        return this.putHeader("content-type","application/json; charset=utf-8")
    }
}